package com.hk.mini;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MiniServer {
    private  static Logger logger = LoggerFactory.getLogger(MiniServer.class);

    private int port;


    public MiniServer(int port) {
        this.port = port;
    }

    public void start(){
       NioEventLoopGroup boss = new NioEventLoopGroup();
       NioEventLoopGroup worker  = new NioEventLoopGroup();


        ServerBootstrap b = new ServerBootstrap();
        try {
            b.group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline().addLast(new MiniDecoder());
                            channel.pipeline().addLast(new MiniServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childOption(ChannelOption.SO_KEEPALIVE,true);
            logger.info("U位程序启动！端口号："+port);
            ChannelFuture future = b.bind(port).sync();

            future.channel().closeFuture().sync();
            logger.info("U位程序关闭！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new MiniServer(502).start();
    }
}
